package com.googlecode.connectlet.tsa;

import java.io.IOException;

import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import sun.security.util.ObjectIdentifier;

public class TimeStampReq {
	private MessageImprint messageImprint;

	public TimeStampReq(MessageImprint messageImprint) {
		this.messageImprint = messageImprint;
	}

	public TimeStampReq(ObjectIdentifier algorithm, byte[] digest) {
		this(new MessageImprint(algorithm, digest));
	}

	public TimeStampReq(byte[] b) throws IOException {
		this(b, 0, b.length);
	}

	public TimeStampReq(byte[] b, int off, int len) throws IOException {
		DerValue[] ders = new DerInputStream(b, off, len).getSequence(0);
		if (ders.length < 2) {
			throw new IOException("Invalid DER Format");
		}
		messageImprint = new MessageImprint(ders[1].toByteArray());
	}

	public MessageImprint getMessageImprint() {
		return messageImprint;
	}

	public ObjectIdentifier getAlgorithm() {
		return messageImprint.getAlgorithm();
	}

	public byte[] getDigest() {
		return messageImprint.getDigest();
	}

	public byte[] getEncoded() throws IOException {
		DerOutputStream tsReq = new DerOutputStream();
		tsReq.putInteger(1);
		tsReq.write(messageImprint.getEncoded());
		tsReq.putBoolean(true);
		DerOutputStream dos = new DerOutputStream();
		dos.write(DerValue.tag_Sequence, tsReq);
		return dos.toByteArray();
	}
}